package com.example.testlxr9096.itemActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.testlxr9096.adapter.DetectItemAdapter;
import com.example.testlxr9096.adapter.GridSpacingItemDecoration;
import com.example.testlxr9096.adapter.IoAdapter;
import com.example.testlxr9096.adapter.WeiQianImageAdapter;
import com.example.testlxr9096.bean.ImageItem;
import com.example.testlxr9096.bean.IoItem;
import com.example.testlxr9096.bean.Item;
import com.example.testlxr9096.ModbusClientManager;
import com.example.testlxr9096.ModbusTCPClient;
import com.example.testlxr9096.R;
import com.example.testlxr9096.adapter.SingleSelectAdapter;
import com.example.testlxr9096.bean.TitleItem;
import com.example.testlxr9096.adapter.TitleItemAdapter;
import com.example.testlxr9096.bean.KeyValuePair;
import com.example.testlxr9096.bean.TestRecord;
import com.example.testlxr9096.database.AppDatabase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class WeiQianTestActivity extends AppCompatActivity {

    private ModbusTCPClient modbusClient,modbusTCPClient2;

    private RecyclerView recyclerView,recyclerViewDecdect,rv_selcet,rv_title;

    private  ScheduledExecutorService scheduler,scheduler1;

    boolean xian1,xian2,xian3,xian4;

    private List<Boolean> xianBooleanList;
    private IoAdapter adapter;

    private int testType = -1;

    private DetectItemAdapter detectItemAdapter;

    private SingleSelectAdapter singleSelectAdapter;

    private WeiQianImageAdapter weiQianImageAdapter;
    private TitleItemAdapter titleItemAdapter;
    private List<IoItem> ioItems;
    private List<IoItem> dectectItems;
    private List<KeyValuePair> keyValuePairsList;
    private List<Item> itemList;
    private List<TitleItem> titleItems;
    private List<Integer> is_1_listPosition;

    private int testPosition  = -1;

    public static  boolean isWeiQian  = true;

    private int[] values;

    List<List<Integer>> listOfLists ;

    private List<ImageItem> imageItemList = new ArrayList<>();
    private  int itemPosition , clickNum;
    private ModbusClientManager manager ;
    private TextView tv_detectResult,tv_checkResult;
    private   Button bt_manualDetect,bt_xun,btn_help,btn_back;
    private boolean isOnClick,isItemSelcet,isStart,isConnect,isStartDetect,isopen,isHandOpen,isSingleOpen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weiqian);

        initData();

        initView();
        initRecycleView();

        initDectRecycleView();
        initXianRecycleView();
        initBottonButtons();

    }

    private void initBottonButtons() {
        // 通过 include 的 id 获取按钮
        View includeView = findViewById(R.id.include_buttons);
        btn_help = includeView.findViewById(R.id.btn_help);
        btn_back = includeView.findViewById(R.id.btn_back);

        btn_help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(WeiQianTestActivity.this, Help.class);
                int numberToSend = 2; // 要传递的数字
                intent.putExtra("key_number", numberToSend);
                startActivity(intent);
            }
        });
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


    }
    private void initData() {
        xianBooleanList = new ArrayList<>();

        manager = ModbusClientManager.getInstance();
        modbusClient = manager.getDevice1();
        modbusTCPClient2 = manager.getDevice2();
        // 初始化 Modbus 客户端（替换为你的设备 IP 和端口）
        ioItems = new ArrayList<>();
        is_1_listPosition = new ArrayList<>();
        itemList = new ArrayList<>();
        titleItems = new ArrayList<>();
        listOfLists = new ArrayList<>(4);
        itemList.clear();
        imageItemList.clear();
        dectectItems = new ArrayList<>();
        String[] XianLangArray = {
                "Q0.A", "Q0.B", "Q0.C", "Q0.D"//,  "Y02", "Y03", "Y04", "Y05", "Y06", "Y07", "Y08", "Y09", "Y0A", "Y0B", "Y0C", "Y0D", "Y0E", "Y0F"

        };
        imageItemList.add(new ImageItem("ST",false,R.drawable.st,0,R.drawable.st_ps,R.drawable.st_ng,0));
        imageItemList.add(new ImageItem("FC",false,R.drawable.fc,0,R.drawable.fc_pass,R.drawable.fc_ng,0));
        imageItemList.add(new ImageItem("LC",false,R.drawable.lc,0,R.drawable.lc_pass,R.drawable.lc_ng,0));
        imageItemList.add(new ImageItem("SC",false,R.drawable.sc,0,R.drawable.sc_pass,R.drawable.sc_ng,0));




        String hexArray[] = null ;

        String[] XianArray = {
                "ST", "LC", "FC", "SC",
        };





            hexArray = XianLangArray;
        for (int i =0;i<hexArray.length;i++){
            ioItems.add(new IoItem(hexArray[i]));
        }

        for (int i =0;i<XianArray.length;i++){
            itemList.add(new Item("待测",XianArray[i],0,0,false));
            titleItems.add(new TitleItem(XianArray[i]));
        }

        for (int i =0;i<64;i++){

               dectectItems.add(new IoItem(String.valueOf(i+1)));



            }
        keyValuePairsList = new ArrayList<>();
        addData();






    }
    public void addData(){
        keyValuePairsList.add(new KeyValuePair("A",42,0));
        keyValuePairsList.add(new KeyValuePair("B",43,0));
        keyValuePairsList.add(new KeyValuePair("C",44,0));
        keyValuePairsList.add(new KeyValuePair("D",45,0));


        xianBooleanList.add(xian1);
        xianBooleanList.add(xian2);
        xianBooleanList.add(xian3);
        xianBooleanList.add(xian4);

    }



    public void clearArray(){


        is_1_listPosition.clear();
        listOfLists.clear();


    }
    private void  closeDetect(){

        isStartDetect = false;

        tv_checkResult.setText("");

        weiQianImageAdapter.clickPosition = -1;
        for (int i = 0; i < imageItemList.size(); i++) {
            setXianState(i,0,"");
        }
        for (int i  = 0;i<dectectItems.size();i++){
            dectectItems.get(i).setState(0);

        }

        for (int i  = 0;i<ioItems.size();i++){
            ioItems.get(i).setSelected(false);

        }
        weiQianImageAdapter.notifyDataSetChanged();

        adapter.notifyDataSetChanged();
        detectItemAdapter.notifyDataSetChanged();


    }

    public void initView(){

        tv_detectResult = findViewById(R.id.tv_result);
        tv_checkResult = findViewById(R.id.tv_checkResult);

        bt_manualDetect = findViewById(R.id.bt_manualDetect);





        bt_manualDetect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                testType = 2;


                if (isHandOpen){
                    bt_manualDetect.setText("开始自动检测");
                    isWeiQian = false;


                    isHandOpen =false;
                    closeDetect();

                }else {
                    bt_manualDetect.setText("停止自动检测");
                    isWeiQian = true;

                    isStartDetect = true;
                    startDecdect();
                    isHandOpen =true;

                }



            }
        });



 }
    public void saveTestResult(String type, String name, String errorInfo, String state) {
        TestRecord testRecord = new TestRecord();
        testRecord.setDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        testRecord.setType(type);
        testRecord.setName(name);
        testRecord.setErrorInfo(errorInfo);
        testRecord.setState(state);


        AppDatabase.getDatabase(WeiQianTestActivity.this).testRecordDao().insert(testRecord);
    }


    public void setXianState(int position,int state,String error){

        imageItemList.get(position).setState(state);
        if (state==1){
//

            if (imageItemList.get(position).getLastStatus()!=imageItemList.get(position).getState()){
                imageItemList.get(position).setLastStatus(imageItemList.get(position).getState());
                saveTestResult("尾纤检测",imageItemList.get(position).getName(),"","通过");

            }


        }else if (state==2){

            if (imageItemList.get(position).getLastStatus()!=imageItemList.get(position).getState()){
                imageItemList.get(position).setLastStatus(imageItemList.get(position).getState());
//                saveTestResult("尾纤检测",imageItemList.get(position).getTitle0(),error,"不通过");

            }
//            AlarmHelper.playBeepAlarm(XianLangTestActivity.this);


        }else {
            itemList.get(position).setTitle("待测");
        }

        itemList.get(position).setSelected(false);


    }
    public void  initRecycleView(){
        recyclerView = findViewById(R.id.recycler_view);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);
        // 添加间距装饰器
        int spacing = getResources().getDimensionPixelSize(R.dimen.grid_spacing);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, spacing, true));
        adapter = new IoAdapter(ioItems);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(position -> {

            isStart = true;
            itemPosition = position;
            isOnClick = true;

            // 切换选中状态
            IoItem item = ioItems.get(position);
            isItemSelcet = item.isSelected();

            item.setSelected(!item.isSelected());


            // 通知适配器该项已更改
            adapter.notifyItemChanged(position);

        });

    }

    public void  initDectRecycleView(){
        recyclerViewDecdect = findViewById(R.id.recyclerLong_view);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 16);
        recyclerViewDecdect.setLayoutManager(layoutManager);

        // 添加间距装饰器
        int spacing = getResources().getDimensionPixelSize(R.dimen.grid_spacing);
        recyclerViewDecdect.addItemDecoration(new GridSpacingItemDecoration(16, spacing, true));
        detectItemAdapter = new DetectItemAdapter(dectectItems);
        recyclerViewDecdect.setAdapter(detectItemAdapter);
        detectItemAdapter.setOnItemClickListener(position -> {

            IoItem item = dectectItems.get(position);
            isItemSelcet = item.isSelected();

            item.setSelected(!item.isSelected());
            detectItemAdapter.notifyItemChanged(position);

        });

    }
    public void  initXianRecycleView(){
        rv_title = findViewById(R.id.rv_title);

        rv_selcet = findViewById(R.id.rv_selcet);
        GridLayoutManager layoutManager = new GridLayoutManager(this,4);
        GridLayoutManager layoutManager1 = new GridLayoutManager(this, 4);

        rv_selcet.setLayoutManager(layoutManager);
        rv_title.setLayoutManager(layoutManager1);

        // 添加间距装饰器
        int spacing = getResources().getDimensionPixelSize(R.dimen.grid_spacing);
        rv_selcet.addItemDecoration(new GridSpacingItemDecoration(4, spacing, true));
        rv_title.addItemDecoration(new GridSpacingItemDecoration(4, spacing, true));

        titleItemAdapter = new TitleItemAdapter(titleItems);
        weiQianImageAdapter = new WeiQianImageAdapter(imageItemList);
        rv_selcet.setAdapter(weiQianImageAdapter);
        rv_title.setAdapter(titleItemAdapter);

    }
    


    public void  readTask(){
        while (isStartDetect){
            //接收数据
            values = modbusTCPClient2.readHoldingRegisters(1, 4, 4);


            if (values != null) {
                clearArray();

                for (int i = 0; i < values.length; i++) {
                    // 转换为二进制字符串（自动去掉前导零）
                    String binary = Integer.toBinaryString(values[i]);
                    int bitLength = binary.length(); // 有效位长度

                    // 存储"1"的位置（从最低位开始计数，0表示最低位）


                    // 从最低位（字符串末尾）向最高位遍历
                    for (int j = binary.length() - 1; j >= 0; j--) {
                        if (binary.charAt(j) == '1') {
                            // 计算位位置：字符串索引i对应的位位置 = (bitLength - 1 - i)
                            int bitPosition = bitLength - 1 - j;
                            switch (i) {
                                case 0:
                                    is_1_listPosition.add(bitPosition);
                                    break;
                                case 1:
                                    is_1_listPosition.add(bitPosition + 16);
                                    break;
                                case 2:
                                    is_1_listPosition.add(bitPosition + 32);
                                    break;
                                case 3:
                                    is_1_listPosition.add(bitPosition + 48);
                                    break;


                            }

                        }
                    }


                }

                for (int i = 0; i < dectectItems.size(); i++) {
                    dectectItems.get(i).setState(0);

                }

                xian1 = is_1_listPosition.contains(42);
                xian2 = is_1_listPosition.contains(43);
                xian3 = is_1_listPosition.contains(44);
                xian4 = is_1_listPosition.contains(45);


                for (int i = 0; i < keyValuePairsList.size(); i++) {


                    if (is_1_listPosition.contains(keyValuePairsList.get(i).getHuang())) {
                        setXianState(i, 1,"");
                        Log.d("lccc", "readTask: " + 111);


                    } else {
                        setXianState(i, 2,"测试不通过");
                        sentTvData(keyValuePairsList.get(i).getKey()+"检测不通过");
                    }

                    //  42 43 44 45
//                    Log.d("readTaskfffff", "readTask:is_1_listPosition  "+i+is_1_listPosition
//                            .get(i));
                }
                if (xian1 && xian2 && xian3 && xian4) {

                    sentTvData("尾纤检测通过");
                } else {


                }





                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                  if (!isStartDetect){
                      closeDetect();
                  }
                        weiQianImageAdapter.notifyDataSetChanged();

                        detectItemAdapter.notifyDataSetChanged();

                    }
                });








            } else {

            }

        }



    }
    Handler handler =new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg != null && msg.obj != null) {
                String resData = msg.obj.toString();
                if (msg.what == 1) {
                    tv_checkResult.setText(resData);

                }

            }
        }
    };
    public void  sentTvData(String str){
        Message message =Message.obtain();


        message.obj = str;
        message.what = 1;
        handler.sendMessage(message);
    }

    public  void  writeTask(){
        if (modbusClient != null) {




            while (isStartDetect ) {
                double result = 0;
                if (isOnClick){
                    itemPosition = itemPosition+10;

                    result = Math.pow(2, itemPosition);
                    if (isItemSelcet){
                        clickNum -= result;
                    }else {
                        clickNum += result;
                    }

                    isOnClick = false;
                }
                   Log.d("lccc", "clickNum: "+clickNum);

                if (clickNum < 65535) {

                    modbusClient.writeMultipleRegisters(1, 32, new int[]{(int)clickNum, 0});

                } else {

                    modbusClient.writeMultipleRegisters(1, 32, new int[]{65535, (int) clickNum-65535});
                }
            }

        }

    }


    public void startDecdect(){


        ioItems.get(0).setSelected(true);
        ioItems.get(1).setSelected(true);
        ioItems.get(2).setSelected(true);
        ioItems.get(3).setSelected(true);
        adapter.notifyDataSetChanged();
        clickNum = 15360;


        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler1 = Executors.newSingleThreadScheduledExecutor();

        // 2. 定义任务内容
        Runnable task = () -> {
            writeTask();

        };

        Runnable task1 = () -> {
            readTask();

        };
        scheduler.scheduleAtFixedRate(task, 0, 500, TimeUnit.MILLISECONDS);

        scheduler1.scheduleAtFixedRate(task1, 0, 500, TimeUnit.MILLISECONDS);

    }




    @Override
    protected void onDestroy() {
        super.onDestroy();
        isStart = false;
        isStartDetect = false;
        if (scheduler!=null){
            scheduler.shutdown();
        }
        if (scheduler1!=null){
            scheduler1.shutdown();
        }



    }

    @Override
    protected void onStop() {
        super.onStop();
        isWeiQian  =false;
        isStart = false;
        isStartDetect = false;
        if (scheduler!=null){
            scheduler.shutdown();
        }
        if (scheduler1!=null){
            scheduler1.shutdown();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isStart = false;
        isWeiQian = false;
        isStartDetect = false;
        if (scheduler!=null){
            scheduler.shutdown();
        }
        if (scheduler1!=null){
            scheduler1.shutdown();
        }

    }
}